package com.wlyuan.open.scanner.repository.impl;

import com.wlyuan.open.scanner.application.factory.SyncFactory;
import com.wlyuan.open.scanner.assembler.ScannerDriverAssembler;
import com.wlyuan.open.scanner.config.GroupProperties;
import com.wlyuan.open.scanner.dao.entity.DriverDO;
import com.wlyuan.open.scanner.dao.mapper.DriverMapper;
import com.wlyuan.open.scanner.domain.driver.Driver;
import com.wlyuan.open.scanner.domain.driver.DriverConvert;
import com.wlyuan.open.scanner.repository.DriverRepository;
import com.wlyuan.open.scanner.utils.GroupCreateKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DriverRepositoryImpl implements DriverRepository {
    private final DriverMapper driverMapper;
    private final SyncFactory syncFactory;
    private final GroupProperties groupProperties;

    @Override
    public List<Driver> list() {
        logger.info("驾驶证编号不为空,公司ID > 0");
        List<DriverDO> list = driverMapper.list();
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        logger.info("老数据数据量，size：{}", list.size());
        //list = removeDuplicate(list);
        //logger.info("根据驾驶证编号和所属公司（租户id）去重后数据量，size：{}", list.size());
        return DriverConvert.convert(list);
    }

    @Override
    public Driver getById(Long driverId) {
        return Optional.ofNullable(driverId).map(id -> {
            var driver = driverMapper.getById(id);
            return DriverConvert.convert(driver);
        }).orElse(null);
    }

    @Override
    public List<Long> getByTime(String startTime, String endTime) {
        return driverMapper.getByTime(startTime, endTime);
    }

    @Override
    public List<Long> getByTenantIdTime(Long tenantId, String startTime, String endTime) {
        return driverMapper.getByTenantIdTime(tenantId, startTime, endTime);
    }

    @Override
    public void getByTenantId(Long tenantId) {
        Optional.ofNullable(tenantId).ifPresent(tenant -> {
            var list = driverMapper.getByTenantId(tenant);
            if (CollectionUtils.isEmpty(list)) {
                logger.info("根据租户{}查询司机数据为0", tenant);
                return;
            }
            logger.info("根据租户{}查询司机数据为{}", tenant, list.size());
            list.forEach(d -> {
                if (groupProperties.groupTenantList().contains(d.getDriverCompanyid())) {
                    d.setDriverCreator(0L);
                    d.setDriverUpdater(0L);
                }
                var data = DriverConvert.convert(d);
                syncFactory.sync(ScannerDriverAssembler.assemble(data));
            });
        });
    }

    private List<DriverDO> removeDuplicate(List<DriverDO> list) {
        //根据驾驶证编号 和 所属公司(租户)id 去重 取最新的数据
        Map<String, List<DriverDO>> mapList = list.stream().filter(x -> StringUtils.isNotBlank(x.getDriverSn()))
                .collect(Collectors.groupingBy(item -> GroupCreateKey.createKey(item.getDriverSn(), String.valueOf(item.getDriverCompanyid())), LinkedHashMap::new, Collectors.toList()));

        return mapList.values().stream().map(values -> values.stream().max(Comparator.comparing(DriverDO::getDriverId)).orElse(null)).collect(Collectors.toList());
    }

}
